package ua.pp.pycb6a.seposition.analysis;

import static ua.pp.pycb6a.seposition.helper.LoggerHelper.getLogger;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.encodeUri;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.getNode;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.getNodeList;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.getPageContent;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.substringBetween;
import static ua.pp.pycb6a.seposition.helper.PropertyHelper.getKeywords;
import static ua.pp.pycb6a.seposition.helper.PropertyHelper.getWebAddress;
import static ua.pp.pycb6a.seposition.helper.WriterHelper.getWriter;
import static ua.pp.pycb6a.seposition.helper.WriterHelper.writeAnalysisResult;
import static ua.pp.pycb6a.seposition.helper.WriterHelper.writeTitle;

public class GoogleAnalysis {

    private static final String SEARCH_ENGINE = "http://www.google.com";
    private static final int GOOGLE_NUMBER = 10;
    private int position = 0;
    private String uri;

    private String xpathLink = ".//div[@class='s']/preceding-sibling::h3[@class='r']/a[contains(@href, '"
            + getWebAddress() + "')]";

    private String xpathCount = ".//div[@class='s']/preceding-sibling::h3[@class='r']/a";

    private String xpathButtonNext = ".//a[@style = 'text-align:left'][contains(@href, '/search?q=')]";

    public void analyse() {

        writeTitle(SEARCH_ENGINE);

        for (String keyword : getKeywords()) {

            getWriter().print("\nREQUEST: " + keyword);
            getLogger().info("REQUEST: " + keyword);

            search(keyword);
            writeAnalysisResult(position, uri);
            position = 0;
        }
    }

    private void search(String keyword) {

        int count = 0;
        int page = 0;
        outer: do {

            getPageContent(encodeUri(SEARCH_ENGINE + "/search?q=" + keyword
                    + "&start=" + page));

            for (int i = 0; i < getNodeList(xpathCount).getLength(); i++) {

                count++;

                if (getNode(xpathLink) != null) {

                    position = count;

                    uri = substringBetween(getNode(xpathLink + "/@href")
                            .getTextContent(), "/url?q=", "&amp;");
                    break outer;
                }
            }

            if (getNode(xpathButtonNext) != null) {

                page += GOOGLE_NUMBER;
            }

        } while (getNode(xpathButtonNext) != null);

    }
}